#!/user/bin/env python3
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# @Time:       2024/5/31 14:12
# Author:      003
# @File:       app.py
# @Python:     3.11
"""
"""
# -------------------------------------------------------------------------------
from flask import Flask
from flask import jsonify, has_request_context, copy_current_request_context, request
from lxml import etree
from utils.http_helper import HttpHelp
import json
import os
from files import index_page

app = Flask(__name__)


@app.route('/')
def hello_world():
    import time
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    return 'Hello, Docker!  t={:}'.format(timestamp)


@app.route('/hidden_fields', methods=['POST'])
def get_hidden_field():
    """__RequestVerificationToken 获取页面中 隐藏表单域"""
    try:

        # if not os.path.exists('data'):
        #     os.makedirs('data')

        html_content = request.get_data(as_text=True)
        tree = etree.HTML(html_content)
        fields = tree.xpath('//input[@type="hidden"]')
        alst = []
        for item in fields:
            print(item.attrib)
            alst.append({"name": item.attrib['name'], "value": item.attrib['value']})
        # if 'data' in data:  # 判断json是否有包含一个key
        #     data = data['data']  # 文件下载是没有data 格式的
        # if data['contentType'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
        #     HttpHelp.base64ToFile('/files' + os.sep + data['fileDownloadName'], data['fileContents'])
        #     pass

        return jsonify({'data': alst, 'msg': "", 'statusCode': 0, 'success': True})
    except Exception as ex:
        print(ex)
        return jsonify({'data': "", 'msg': ex.args[0], 'statusCode': 500, 'success': False})


# region base64文件转存文件
@app.route('/base64', methods=['POST','GET'])
def get_file_frombase64():
    '''  base64
    json{
        "fileContents":"base64",
        "contentType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "fileDownloadName": "待开发票.xlsx",
        "lastModified": null,
        "entityTag": null,
        "enableRangeProcessing": false
    }  '''

    try:

        # if not os.path.exists('files'):
        #     os.makedirs('files')

        data = json.loads(request.get_data(as_text=True))
        if 'data' in data:  # 判断json是否有包含一个key
            data = data['data']  # 文件下载是没有data 格式的
        if data['contentType'] == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
            HttpHelp.base64ToFile('/files' + os.sep + data['fileDownloadName'], data['fileContents'])
            pass

        return jsonify({'data': "", 'msg': "", 'statusCode': 0, 'success': True})
    except Exception as ex:
        print(ex)
        return jsonify({'data': "", 'msg': ex.args[0], 'statusCode': 500, 'success': False})


# endregion

if __name__ == '__main__':
    app.register_blueprint(index_page, url_prefix="/files")

    app.run(host='0.0.0.0', port=5001)
